import { useState, useEffect } from 'react';
import { Checkbox, Table, Input } from 'antd';
import { useIntl } from 'umi';
import request from '@/utils/request';

const { Search } = Input;
const apiURL = '/api/services/app/Vendor/';
const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize] = useState(10);
  const [dataSource, setDataSource] = useState([]);
  const [keywords, setKeywords] = useState('');
  const [totalCount, setTotalCount] = useState(0);

  const intl = useIntl();

  useEffect(() => {
    fetchDatas();
  }, [pageIndex, keywords]);

  const fetchDatas = () => {
    setLoading(true);
    request(apiURL + 'GetList', {
      method: 'GET',
      params: {
        SkipCount: (pageIndex - 1) * pageSize,
        MaxResultCount: pageSize,
        keywords,
        pType: props.pType,
      },
    }).then((response) => {
      if (response) {
        if (response.success) {
          setDataSource(response.result?.items);
          setTotalCount(response.result?.totalCount);
          setLoading(false);
        }
        setLoading(false);
      }
    });
  };

  const setCurrent = (obj?: any) => {
    if (props.setCurrent) {
      props.setCurrent(obj);
    }
  };

  const onSearch = (keywords: string) => {
    setKeywords(keywords);
  };

  const columns = [
    {
      title: intl.formatMessage({ id: 'pages.vendorName' }),
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: intl.formatMessage({ id: 'pages.vendorID' }),
      dataIndex: 'vendorID',
      key: 'vendorID',
    },
    {
      title: intl.formatMessage({ id: 'pages.vendorNum' }),
      dataIndex: 'vendorNum',
      key: 'vendorNum',
    },
    {
      title: intl.formatMessage({ id: 'pages.inactive' }),
      render: (record: any) => (
        <span>
          <Checkbox checked={record.inActive} />
        </span>
      ),
    },
  ];

  return (
    <>
      <Search
        placeholder={intl.formatMessage({ id: 'pages.keywords.search' })}
        allowClear
        enterButton
        onSearch={onSearch}
      />
      <Table
        onRow={(record) => {
          return {
            onClick: () => {},
            onDoubleClick: () => {
              setCurrent(record);
            },
          };
        }}
        pagination={{
          onChange: (page) => {
            setPageIndex(page);
          },
          pageSize,
          total: totalCount,
        }}
        rowKey="id"
        size="small"
        columns={columns}
        dataSource={dataSource}
        loading={loading}
      />
    </>
  );
};

export default ViewPage;
